package com.duowei.diandan.fragment;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.duowei.diandan.R;
import com.duowei.diandan.adapter.CommonFoodAdapter;
import com.duowei.diandan.adapter.PresentOrAddPriceAdapter;
import com.duowei.diandan.adapter.TasteRequiredAdapter;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.app.SqlServerDateTime;
import com.duowei.diandan.bean.food.Meal;
import com.duowei.diandan.bean.food.PresentOrAddPrice;
import com.duowei.diandan.bean.food.Single;
import com.duowei.diandan.bean.food.SingleAndMeals;
import com.duowei.diandan.bean.food.Taste;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.databinding.SingleAndGroupFragmentBinding;
import com.duowei.diandan.db.FoodMenu;
import com.duowei.diandan.db.entry.Dmpzsd;
import com.duowei.diandan.db.entry.Jyxmsz;
import com.duowei.diandan.db.entry.Wmlsb;
import com.duowei.diandan.event.ToastEvent;
import com.duowei.diandan.util.FoodHelper;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 单品(或赠送、加价)和套餐组合
 */
public class SingleAndMealFragment extends Fragment {
    public static final String TAG = "SingleAndMealFragment";

    private SingleAndGroupFragmentBinding mBinding;

    private Single mSingle;
    private SingleAndMeals mSingleAndMeals;

    private TasteRequiredAdapter mTasteRequiredAdapter;

    private PresentOrAddPriceAdapter mPresentAdapter;
    private PresentOrAddPriceAdapter mAddPriceAdapter;

    private Observer mDataUpdateObserver = new Observer() {
        @Override
        public void update(Observable o, Object arg) {
            if (mSingle != null) {
                FoodMenu.getInstance().querySingle(mSingle.getItem().getXmbh(), single -> {

                    if (single != null) {
                        setupView(single, null);
                        mSingle = single;

                    } else {
                        if (mOnClickListener != null) {
                            mOnClickListener.onCloseClick();
                        }
                    }
                });

            } else if (mSingleAndMeals != null) {
                FoodMenu.getInstance().querySingleAndMeals(
                        mSingleAndMeals.getSingle().getItem().getXmbh(), singleAndMeals -> {

                            if (singleAndMeals != null) {
                                setupView(singleAndMeals.getSingle(), singleAndMeals.getMealList());
                                mSingleAndMeals = singleAndMeals;

                            } else {
                                if (mOnClickListener != null) {
                                    mOnClickListener.onCloseClick();
                                }
                            }
                        });
            }
        }
    };

    public static SingleAndMealFragment newInstance(SingleAndMeals singleAndMeals) {

        Bundle args = new Bundle();
        args.putSerializable("singleAndMeals", singleAndMeals);

        SingleAndMealFragment fragment = new SingleAndMealFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public static SingleAndMealFragment newInstance(Single single) {

        Bundle args = new Bundle();
        args.putSerializable("single", single);

        SingleAndMealFragment fragment = new SingleAndMealFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mSingleAndMeals = (SingleAndMeals) getArguments().getSerializable("singleAndMeals");
            mSingle = (Single) getArguments().getSerializable("single");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_single_and_meal,
                container, false);

        // 返回按钮
        mBinding.backButton.setOnClickListener(v -> {
            if (mOnClickListener != null) {
                mOnClickListener.onCloseClick();
            }
        });

        // 确定按钮
        mBinding.confirmButton.setOnClickListener(v -> {
            Single single = null;
            Jyxmsz jyxmsz = null;

            if (mSingle != null) {
                single = mSingle;
                jyxmsz = mSingle.getItem();
            } else if (mSingleAndMeals != null) {
                single = mSingleAndMeals.getSingle();
                jyxmsz = mSingleAndMeals.getSingle().getItem();
            }

            String checkedTasteStr = null;
            if (mTasteRequiredAdapter != null) {
                checkedTasteStr = mTasteRequiredAdapter.getCheckedString();

                if (TextUtils.isEmpty(checkedTasteStr)) {
                    EventBus.getDefault().post(new ToastEvent("请先选择口味", false));
                    return;
                }
            }

            List<Wmlsb> childWmlsbList = new ArrayList<>();
            // 赠送处理
            if (mPresentAdapter != null && mPresentAdapter.getCheckedItem() != null) {
                Jyxmsz jyxmsz1 = mPresentAdapter.getCheckedItem().getItem();

                Wmlsb childWmlsb = new Wmlsb(jyxmsz1, false, 0);
                childWmlsb.setSfzs("1");
                childWmlsb.setBy13("赠送");
                childWmlsb.setSqrxm("买赠设置");
                childWmlsb.setZssj(SqlServerDateTime.getInstance().getNowServerDateTime());
                childWmlsbList.add(childWmlsb);
            }
            // 加价
            if (mAddPriceAdapter != null && mAddPriceAdapter.getCheckedItem() != null) {
                Jyxmsz jyxmsz1 = mAddPriceAdapter.getCheckedItem().getItem();

                Wmlsb childWmlsb = new Wmlsb(jyxmsz1, false, 0);
                childWmlsb.setBy13("加价促销");
                childWmlsbList.add(childWmlsb);
            }

            EventBus.getDefault().post(new ToastEvent(jyxmsz.getXmmc() + " +1"));
            OrderList.getInstance().addSingle(single, checkedTasteStr, childWmlsbList);

            if (mOnClickListener != null) {
                mOnClickListener.onCloseClick();
            }
        });

        setData();

        return mBinding.getRoot();
    }

    private void setData() {
        if (mSingle != null) {
            setupView(mSingle, null);

        } else if (mSingleAndMeals != null) {
            setupView(mSingleAndMeals.getSingle(), mSingleAndMeals.getMealList());

        } else {
            if (mOnClickListener != null) {
                mOnClickListener.onCloseClick();
            }
        }
    }

    private void setupView(Single single, List<Meal> mealList) {
        if (single != null) {
            // 当前单品
            FoodHelper.setCoverImage(single.getImgNo(), mBinding.coverView);
            FoodHelper.setPrice(single, mBinding.priceDescView);
            mBinding.nameView.setText(single.getName());

            // 必选口味选择
            if (single.getTasteList() != null && single.getTasteList().size() > 0) {
                EventBus.getDefault().post(new ToastEvent("请选择口味", false));

                mBinding.tasteRequiredLayout.setVisibility(View.VISIBLE);

                FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext(), FlexDirection.ROW);
                mBinding.tasteRecyclerView.setLayoutManager(layoutManager);

                List<Taste> tasteList = new ArrayList<>();
                for (Dmpzsd d : single.getTasteList()) {
                    tasteList.add(new Taste(d));
                }
                mTasteRequiredAdapter = new TasteRequiredAdapter(tasteList);
                mBinding.tasteRecyclerView.setAdapter(mTasteRequiredAdapter);
            } else {
                mBinding.tasteRequiredLayout.setVisibility(View.GONE);
            }

            // 赠送促销
            if (single.getPresentList() != null && single.getPresentList().size() > 0) {
                mBinding.presentLayout.setVisibility(View.VISIBLE);

                List<PresentOrAddPrice> list = new ArrayList<>();
                for (Jyxmsz j : single.getPresentList()) {
                    list.add(new PresentOrAddPrice(j, false));
                }

                GridLayoutManager layoutManager = new GridLayoutManager(getContext(),
                        Settings.COLUMN_PROMOTION, GridLayoutManager.VERTICAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                };
                layoutManager.setAutoMeasureEnabled(true);
                mBinding.presentRecyclerView.setLayoutManager(layoutManager);
                mPresentAdapter = new PresentOrAddPriceAdapter(list);
                mBinding.presentRecyclerView.setAdapter(mPresentAdapter);

            } else {
                mBinding.presentLayout.setVisibility(View.GONE);
            }

            // 加价促销
            if (single.getAddPriceList() != null && single.getAddPriceList().size() > 0) {
                mBinding.addPriceLayout.setVisibility(View.VISIBLE);

                List<PresentOrAddPrice> list = new ArrayList<>();
                for (Jyxmsz j : single.getAddPriceList()) {
                    list.add(new PresentOrAddPrice(j, true));
                }

                GridLayoutManager layoutManager = new GridLayoutManager(getContext(),
                        Settings.COLUMN_PROMOTION, GridLayoutManager.VERTICAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                };
                layoutManager.setAutoMeasureEnabled(true);
                mBinding.addPriceRecyclerView.setLayoutManager(layoutManager);
                mAddPriceAdapter = new PresentOrAddPriceAdapter(list);
                mBinding.addPriceRecyclerView.setAdapter(mAddPriceAdapter);

            } else {
                mBinding.addPriceLayout.setVisibility(View.GONE);
            }
        }

        if (mealList != null && mealList.size() > 0) {
            // 推荐套餐
            mBinding.mealLayout.setVisibility(View.VISIBLE);

            GridLayoutManager layoutManager = new GridLayoutManager(getContext(),
                    Settings.COLUMN_COMBO, GridLayoutManager.VERTICAL, false) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            layoutManager.setAutoMeasureEnabled(true);
            mBinding.mealRecyclerView.setLayoutManager(layoutManager);
            CommonFoodAdapter adapter = new CommonFoodAdapter(mealList);
            mBinding.mealRecyclerView.setAdapter(adapter);
            adapter.setOnItemClickListener(food -> {
                if (mOnClickListener != null) {
                    mOnClickListener.onMealClick((Meal) food);
                }
            });

        } else {
            mBinding.mealLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        FoodMenu.getInstance().addObserver(mDataUpdateObserver);
    }

    @Override
    public void onStop() {
        super.onStop();
        FoodMenu.getInstance().deleteObserver(mDataUpdateObserver);
    }

    // --
    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    private OnClickListener mOnClickListener;

    public interface OnClickListener {
        void onCloseClick();

        void onMealClick(Meal meal);
    }
}
